//
//  ClubPushDynamicViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/28.
//

import UIKit
import ZLPhotoBrowser
import Photos

class ClubPushDynamicViewController: ClubBaseViewController {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private let closeButton = c_make_ex(UIButton.self)
        .image("Common_close").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("发布到圈子").font(16.font_semiBold).color(.black).end()
    private let sendButton = c_make_ex(UIButton.self)
        .image("Square_pushEnable").image("Square_pushDisable", state: .disabled).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(18.0.Scale).border(.black.alpha(0.1), width: 1.5).end()
    private let placeholderLabel = c_make_ex(UILabel.self)
        .text("在此处输入内容...").font(15.font_medium).color("#AEB0B3").end()
    // 创建UITextView
    private let textView: UITextView = {
        let tv = UITextView()
        tv.font = 15.font_medium
        tv.textColor = "#47494D".toColor
        tv.tintColor = "#47494D".toColor
//        tv.isScrollEnabled = false  // 禁止滚动
        tv.backgroundColor = .clear
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()
    private let functionView = ClubDynamicFunctionView()
    private let searchView = ClubDynamicSearchView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var gameModels: [ClubDynamicGameModel]?
    var topicModels: [ClubDynamicGameModel]?
    
    private var hasVideo = false
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    private var imageUrlArr = [String]()
    private var subject_id: [String] = []
    private var gid: [String] = []
    private var oldText: NSAttributedString?
    private var tempArray = [ClubDynamicGameModel]()
    // 定义富文本的范围
    var richTextRange = [NSRange]()
    var updateData: (() -> Void)?
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    iconImageView
                    textView.subviews{
                        placeholderLabel
                    }
                    functionView
                    collectionView
                }
            }
            closeButton
            titleLabel
            sendButton
            searchView
        }
        
        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(0).leading(0).width(.screenWidth).bottom(0)
        containerView.fillContainer().width(.screenWidth)
        closeButton.top(.statusHeight).leading(0).width(56.0.Scale).height(44.0.Scale)
        titleLabel.Leading == closeButton.Trailing
        titleLabel.CenterY == closeButton.CenterY
        sendButton.trailing(0).top(.statusHeight).height(44.0.Scale).width(88.0.Scale)
        iconImageView.leading(10).top(.navi_height+4.0).size(36.0.Scale)
        textView.leading(56.0.Scale).trailing(12.0.Scale).top(.navi_height+8.0.Scale).height(37.0.Scale)
        placeholderLabel.leading(2).top(2)
        functionView.leading(56.0.Scale).trailing(0).height(33.0.Scale)
        functionView.Top == textView.Bottom + 3.0.Scale
        searchView.leading(0).trailing(0).bottom(0)
        searchView.Top == textView.Bottom + 5.0.Scale
        collectionView.leading(0).trailing(0).height(0).bottom(.tabBar_height)
        collectionView.Top == functionView.Bottom + 8.0.Scale
        
        sendButton.isEnabled = false
        textView.delegate = self
        searchView.isHidden = true
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        functionView.imgStr = ["Square_pushGame","Square_pushTopic","Square_pushPic"]
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2.0.Scale
        layout.minimumInteritemSpacing = 2.0.Scale
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 56.0.Scale, bottom: 0, right: 16.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameCircleCell.self, forCellWithReuseIdentifier: ClubGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        functionView.functionButtonBlock = { funcID in
            
            if funcID == 0 {
                
                self.searchView.isHidden = false
                self.searchView.searchType = 2
                self.functionView.isHidden = true
            } else if funcID == 1 {
                
                self.searchView.isHidden = false
                self.searchView.searchType = 1
                self.functionView.isHidden = true
            } else if funcID == 2 {
                //添加图片、视频
                self.checkPhotoLibraryPermission()
            }
            
            self.textView.resignFirstResponder()
        }
        
        searchView.searchBlock = { md in
            
            if !self.searchView.isHidden {
                self.searchView.isHidden = true
                self.functionView.isHidden = false
            }
            if md.type == "2" {
                //游戏
                self.insertRichText(in: self.textView, image: "Square_gameTag".toImage, model: md, textColor: "#3D9399".toColor, imageSize: CGSizeMake(20, 20))
                self.textView.becomeFirstResponder()
            }else {
                //话题
                self.insertRichText(in: self.textView, image: nil, model: md, textColor: "#E57617".toColor, imageSize: .zero)
                self.textView.becomeFirstResponder()
            }
        }
        searchView.isShowSearchView = {
            if !self.searchView.isHidden {
                self.searchView.isHidden = true
                self.functionView.isHidden = false
            }
        }
        
        iconImageView.loadImage(url: ClubUser.face)
        sendButton.addTarget(self, action: #selector(clickSendButton), for: .touchUpInside)
    }
    
    @objc private func clickCloseButton(){
        self.dismiss(animated: true)
    }
    
}

//MARK: Action
extension ClubPushDynamicViewController {
    
   private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
            
        switch status {
            case .authorized:
                // 已经授权，继续访问相册
            DispatchQueue.main.async {
                self.showPhotoLibrary()
            }
                
            case .denied, .restricted:
                // 用户拒绝或受限，无法访问相册
                print("用户拒绝访问相册")
            case .notDetermined:
                // 用户还没有决定是否允许访问，进行请求
                PHPhotoLibrary.requestAuthorization { newStatus in
                    if newStatus == .authorized {
                        // 用户授权，继续访问相册
                        DispatchQueue.main.async {
                            self.showPhotoLibrary()
                        }
                    } else {
                        print("用户拒绝访问相册")
                    }
                }
        @unknown default:
                print("未知的权限状态")
        }
    }
    
    private func showPhotoLibrary() {
        if hasVideo {
            "请删除视频后重选".toast_error
            return
        }
        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.maxSelectCount = 9
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowSelectVideo = images.count == 0
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = .max
        config.maxRecordDuration = .max
        config.maxSelectVideoDuration = .max
        config.saveNewImageAfterEdit = false
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        config.saveNewImageAfterEdit = false
        
        let ac = ZLPhotoPreviewSheet(selectedAssets:assets)
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            self?.hasVideo = assets.first?.mediaType == .video
            self?.images = images
            self?.assets = assets
            self?.loadImageData()
        }
        ac.showPhotoLibrary(sender: self)
    }
    
    @objc private func clickSendButton(){

        let fullText = NSMutableString()
        textView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: textView.attributedText.length), options: []) { attributes, range, _ in
            if let attachment = attributes[.attachment] as? NSTextAttachment {
                // 发现图片，添加占位符 "[图片]"
                fullText.append("[图片]")
            } else {
                // 纯文本部分，直接追加到 fullText 中
                let substring = (textView.attributedText.string as NSString).substring(with: range)
                fullText.append(substring)
            }
        }
        if fullText.length <= 0 {
            "请输入发布内容".toast_error
            return
        }
        ToastUtil.show()
        if hasVideo {
            ZLPhotoManager.fetchAssetFilePath(asset: self.assets.first!) { path in
                let videoData =  try? Data(contentsOf: URL(string: path ?? "")!)
                let suffix = URL(string: path ?? "")!.pathExtension
                RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images.first!) { urlString in
                    RaeRequestParameterConfig.shared.uploadVideo(record: videoData!, suffix: suffix) { videoUrl in
                        self.addDynamic(content: fullText as String, imgs: urlString, video: videoUrl)
                    } failure: { errorMessage in
                        ToastUtil.dismiss()
                        errorMessage.toast_error
                    } progress: { pro in
                        
                    }

                } failure: { errorMessage in
                    ToastUtil.dismiss()
                }

            }
        }else{
            if self.images.count > 0 {
                updateImage(content: fullText as String)
            }else{
                addDynamic(content: fullText as String, imgs: "", video: "")
            }
        }
    }
    
    private func addDynamic(content: String, imgs: String, video: String){
        
        Task{
            self.subject_id.removeAll()
            self.gid.removeAll()
            for md in tempArray {
                if md.type == "1" {
                    subject_id.append(md.id)
                }else if md.type == "2" {
                    gid.append(md.id)
                }
            }
            let subject_String = self.subject_id.joined(separator: ",")
            let gid_string = self.gid.joined(separator: ",")
            let dict: [String: String] = ["content": content, "imgs": imgs, "video": video, "subject_id": subject_String, "gid": gid_string]
            RaeRequestParameterConfig.shared.pushDynamic(param: dict) { finish in
                "发布成功".toast_success
                self.dismiss(animated: true){
                    self.updateData?()
                }
            } failure: { error in
                
            }
            ToastUtil.dismiss()
        }
    }
    
    private func updateImage(content: String){
        self.imageUrlArr.removeAll()
        let upLoadImageGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "upLoadImageGroup")
        for i in 0..<images.count {
            upLoadImageGroup.enter()
            
            workingQueue.async {

                RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images[i]) { urlString in
                    self.imageUrlArr.append(urlString)
                    upLoadImageGroup.leave()
                } failure: { errorMessage in
                    upLoadImageGroup.leave()
                }
            }
        }
        
        upLoadImageGroup.notify(queue: workingQueue) {
            self.addDynamic(content: content, imgs: self.imageUrlArr.joined(separator: ","), video: "")
        }
    }
}

//MARK: TextView
extension ClubPushDynamicViewController: UITextViewDelegate {
    
    // UITextViewDelegate 方法
    func textViewDidChange(_ textView: UITextView) {
        // 计算文本内容的高度
        let size = CGSize(width: textView.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)
        // 更新高度约束
        if estimatedSize.height > 248.0.Scale {
            textView.heightConstraint?.constant = 248.0.Scale
        }else{
            textView.heightConstraint?.constant = estimatedSize.height
        }

        // 根据内容决定是否隐藏占位符
        placeholderLabel.isHidden = !textView.text.isEmpty
        sendButton.isEnabled = !textView.text.isEmpty
        changeToRichText(textView)
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        // 开始编辑时隐藏占位符
        placeholderLabel.isHidden = true
    }
        
    func textViewDidEndEditing(_ textView: UITextView) {
        // 结束编辑时，如果内容为空，显示占位符
        if textView.text.isEmpty {
            placeholderLabel.isHidden = false
        }
    }
    
    // 监听删除操作
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text.isEmpty { // 是删除操作
//            let attributedText = textView.attributedText!
//            // 判断要删除的是否是特殊颜色的文字或图片
//            if range.location > 0 {
//                let previousRange = NSRange(location: range.location - 1, length: 1)
//                
//                // 获取要删除位置的属性
//                let attributes = attributedText.attributes(at: previousRange.location, effectiveRange: nil)
//                
//                if let color = attributes[.foregroundColor] as? UIColor, color == "#3D9399".toColor {
//                    // 找到整块需要删除的范围，包括图片
//                    var fullRange = findSpecialBlockRange(at: range.location, in: textView.attributedText)
//                    if fullRange.length > textView.text.count {
//                        fullRange.length -= 1
//                    }
//                    textView.textStorage.deleteCharacters(in: fullRange)
//                    self.oldText = textView.attributedText
//                    return false
//                }
//                if let color = attributes[.foregroundColor] as? UIColor, color == "#E57617".toColor {
//                    // 找到整块需要删除的范围，包括图片
//                    var fullRange = findTopicRange(at: range.location, in: textView.attributedText)
//                    if fullRange.length > textView.text.count {
//                        fullRange.length -= 1
//                    }
//                    textView.textStorage.deleteCharacters(in: fullRange)
//                    self.oldText = textView.attributedText
//                    return false
//                }
//            }
//            updateRichTextRanges()
//            changeToRichText(self.textView)
            // 检查要删除的范围是否与缓存的富文本范围相交
            for (index, richRange) in richTextRange.enumerated() {
                if NSIntersectionRange(richRange, range).length > 0 {
                // 确保 richRange 不越界
                if richRange.location < textView.textStorage.length {
                    let adjustedRange = NSIntersectionRange(richRange, NSRange(location: 0, length: textView.textStorage.length))
                        textView.textStorage.deleteCharacters(in: adjustedRange)
                        self.tempArray = tempArray.filter { $0.range != richRange }
                        richTextRange.remove(at: index)
                        self.oldText = textView.attributedText
                    }
                    return false
                }
            }
        }
        return true
    }
        
    // Helper function to find the full range of the special block (图片 + 特殊颜色字符)
    func findSpeicalRange(at location: Int, in attributedText: NSAttributedString, color: UIColor) -> NSRange {
        let fullText = attributedText.string as NSString
        let length = fullText.length

        // 向前找到特殊文本块的开始
        var startIndex = location
        while startIndex > 0 {
            let attributes = attributedText.attributes(at: startIndex, effectiveRange: nil)
            if attributes[.foregroundColor] as? UIColor != color{
                break
            }
            startIndex -= 1
        }

        // 向后找到特殊文本块的结束
        var endIndex = location
        while endIndex < length {
            let attributes = attributedText.attributes(at: endIndex, effectiveRange: nil)
            if attributes[.foregroundColor] as? UIColor != color {
                break
            }
            endIndex += 1
        }

        // 计算完整范围
        return NSRange(location: startIndex, length: endIndex - startIndex)
    }
    
    func changeToRichText(_ textView: UITextView) {
        guard let selectedRange = textView.selectedTextRange else { return }

        // 获取当前输入方式是否为拼音输入，避免中断拼音输入
        if textView.markedTextRange != nil {
            // 如果有标记文字（拼音输入未完成），不进行富文本更新
            return
        }

        // 获取新的 attributedText
        let currentAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
//        let newText = textView.text
        
        // 确保 oldText 不为空
        guard let oldText = self.oldText?.string else {
            self.oldText = currentAttributedText
            return
        }
        
        let count = currentAttributedText.string.count - oldText.count
        if count <= 0 {
            return
        }
        
        // 获取新增的文本
        let range = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        let inputRange = NSRange(location: range - count, length: count)
        
        // 判断新输入内容是否为 emoji
        let newInput = (textView.text as NSString).substring(with: inputRange)
        if isEmoji(newInput) {
            // 对于 emoji 的特殊处理
            return
        }
        
        // 设置新输入字符的默认样式
        let newAttributedString = NSAttributedString(string: newInput, attributes: [
            .font: 15.font_medium!,
            .foregroundColor: "#47494D".toColor
        ])
        
        // 替换未设置样式的文本
        currentAttributedText.replaceCharacters(in: inputRange, with: newAttributedString)
        
        // 更新 textView 的 attributedText，并恢复光标位置
        textView.attributedText = currentAttributedText
        self.oldText = currentAttributedText
        if let newPosition = textView.position(from: textView.beginningOfDocument, offset: range) {
            textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
        }
    }

    // 判断是否为 emoji
    func isEmoji(_ text: String) -> Bool {
        return text.unicodeScalars.contains { $0.properties.isEmojiPresentation }
    }

    
    func insertRichText(in textView: UITextView, image: UIImage?, model: ClubDynamicGameModel, textColor: UIColor, imageSize: CGSize) {
        // 创建富文本
        let richText = NSMutableAttributedString()
        var md = model
        var text = model.name + " "
        if model.type == "1" {
            text = " #" + model.name + " "
        }
        var startIndex = 0
        // 添加现有内容
        if let currentText = textView.attributedText {
            richText.append(currentText)
            startIndex = currentText.length
        }

        let gameText = NSMutableAttributedString()
        // 插入图片
        if let image = image {
            gameText.append(NSAttributedString(string: " "))
            let attachment = NSTextAttachment()
            attachment.image = image
            attachment.bounds = CGRect(x: 0, y: -7, width: imageSize.width, height: imageSize.height)
            let imageString = NSAttributedString(attachment: attachment)
            gameText.append(imageString)
        }

        // 插入文本
        let attributedText = NSAttributedString(string: text, attributes: [.foregroundColor: textColor])
        gameText.append(attributedText)
        // 记录这个富文本块的范围
      
        let range = NSRange(location: startIndex, length: gameText.length)
        richTextRange.append(range)
        md.range = range
        self.tempArray.append(md)
        
        richText.append(gameText)
        // 保持现有的字体设置
        let entireRange = NSRange(location: 0, length: richText.length)
        richText.addAttribute(.font, value: 15.font_medium!, range: entireRange)

        // 插入后的光标位置
        let newCursorPosition = richText.length

        // 更新UITextView的内容并设置光标位置
        textView.attributedText = richText
        self.oldText = richText
        if let newPosition = textView.position(from: textView.beginningOfDocument, offset: newCursorPosition) {
            textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
        }
        
        // 计算文本内容的高度
        let size = CGSize(width: textView.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)
        // 更新高度约束
        textView.heightConstraint?.constant = estimatedSize.height
    }

    // 监听光标变化
    func textViewDidChangeSelection(_ textView: UITextView) {
        for richRange in richTextRange {
            // 检查光标是否进入了某个富文本块的范围
            if NSLocationInRange(textView.selectedRange.location, richRange) {
                // 如果光标位于富文本内部，移动到富文本块的后面
                let newLocation = richRange.location + richRange.length
                if textView.selectedRange.location < newLocation {
                    textView.selectedRange = NSRange(location: newLocation, length: 0)
                }
            }
        }
    }

    func updateRichTextRanges(){
        var tempRange = richTextRange
        for richRange in richTextRange {
            var rang = richRange
            rang.location -= 1
            tempRange.append(rang)
        }
        richTextRange = tempRange
    }
}

//MARK: UICollectionViewDelegate, UICollectionViewDataSource
extension ClubPushDynamicViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if hasVideo {
            return 1
        }else{
            return images.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameCircleCell.description(), for: indexPath) as? ClubGameCircleCell else { return UICollectionViewCell() }
        pageCell.imageView.image = images[indexPath.row]
        pageCell.playImage.isHidden = !hasVideo
        pageCell.index = indexPath.row
        pageCell.delButton.isHidden = false
        pageCell.delBlock = { delIndex in
            self.images.remove(at: delIndex)
            self.assets.remove(at: delIndex)
            self.hasVideo = false
            self.collectionView.reloadData()
        }
        pageCell.layoutIfNeeded()
        if images.count == 1 {
            pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8.0.Scale)
        }else if images.count == 2 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 3 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 4 || images.count == 5{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
            
        }else if images.count == 6 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 5 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if images.count == 7 || images.count == 8{
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 8 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if hasVideo {
            return CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        }else if images.count == 1 {
            return CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        }else if images.count == 2{
            
            return CGSize (width: (CGFloat.screenWidth - 74.0.Scale)/2.0, height: 90.0.Scale)
        }else{
            
            return CGSize (width: (CGFloat.screenWidth - 76.0.Scale)/3, height: (CGFloat.screenWidth - 76.0.Scale)/3)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = ZLImagePreviewController(datas: self.assets, index: indexPath.row, showSelectBtn: false) { (url) -> ZLURLType in
            if self.hasVideo {
                return .video
            }else {
                return .image
            }
            
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}


//MARK: data
extension ClubPushDynamicViewController {
    
    private func loadImageData(){
        
        if hasVideo {
            
            collectionView.heightConstraint?.constant = 152.0.Scale
        }else {
            
            if images.count == 1 {
                collectionView.heightConstraint?.constant = 152.0.Scale
            }else if images.count == 2 {
                collectionView.heightConstraint?.constant = 90.0.Scale
            }else if images.count > 2 {
                let index = (images.count + 2) / 3
                collectionView.heightConstraint?.constant = (CGFloat.screenWidth - 76.0.Scale)/3 * CGFloat(index)
            }else{
                collectionView.heightConstraint?.constant = 0
            }
        }
        collectionView.reloadData()
    }
}
